package com.wantup.service;

import com.wantup.controller.v6.User;
import com.wantup.model.InMessage;
import com.wantup.model.OutMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @ClassName WebSocketService
 * @Description 简单消息模板用来推送消息。
 * @Author zhaoluowei
 * @Date 2019/6/23  18:08
 * @Version 1.0
 */
@Component
public class WebSocketService {

    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;

    public void sendTopicMessage(String des, InMessage inMessage) {
        for (int i = 0; i < 2; i++) {
            simpMessagingTemplate.convertAndSend(des, new OutMessage().setContent(inMessage.getContent() + "  " + i));
        }
    }


    public void sendChatMessage(InMessage inMessage) {
        System.out.println("/chat/single/" + inMessage.getTo());
        simpMessagingTemplate.convertAndSend("/chat/single/" + inMessage.getTo(), new OutMessage().setContent(inMessage.getFrom() + "  发来的消息  " + inMessage.getContent()));
    }

    /**
     * 获取 jvm 内存情况 使用 runtime
     */
    public void sendServerInfo() {
        //CPU 核数
        int process = Runtime.getRuntime().availableProcessors();

        //空闲内存
        long freeMemory = Runtime.getRuntime().freeMemory();

        //最大内存
        long maxMemory = Runtime.getRuntime().maxMemory();

        String message = "服务器可以处理器 : " + process + "  空闲内存  " + freeMemory + "   最大内存  " + maxMemory;

        simpMessagingTemplate.convertAndSend("/topic2/server_info", new OutMessage().setContent(message));


    }


    public void sendOnlineUser(Map<String, User> onlineUser) {
        String msg = "";
        for (Map.Entry<String, User> entry : onlineUser.entrySet()) {
            msg = msg.concat(entry.getValue().getUsername() + "  ||   ");
        }
        simpMessagingTemplate.convertAndSend("/topic/onlineuser", new OutMessage().setContent(msg));

    }

    public void sendTopicChat(InMessage inMessage) {

        String msg = inMessage.getFrom() + " 发送 " + inMessage.getContent();
        simpMessagingTemplate.convertAndSend("/topic/chat", new OutMessage().setContent(msg));
    }
}
